﻿using Core;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using System.Data;

namespace DAL
{
    public class SysUserInfoDAL : BaseDAL
    {
        #region 用户信息表导入
        /// <summary>
        /// 用户信息表导入
        /// </summary>
        /// <returns></returns>
        public bool GetSysUserInfo()
        {
            using (var conn = new SqlConnection(connection))
            {
                conn.Open();
                conn.Execute("truncate table SysUserInfo;");
            }
            Func<int, int, bool> DownSysUser = (pageIndex, pageSize) =>
            {
                using (WebClient wc = new WebClient())
                {
                    wc.Encoding = System.Text.Encoding.GetEncoding("utf-8");
                    string strSui = string.Empty;
                    try
                    {
                        strSui = wc.DownloadString(ConfigHelper.GetConfigString("RemoteUrl") + "/Ayyfford/GetSysUserInfo?pageIndex=" + pageIndex + "&pageSize=" + pageSize);
                    }
                    finally
                    {
                        wc.Dispose();
                    }
                    if (!string.IsNullOrWhiteSpace(strSui))
                    {
                        var lsui = JsonConvert.DeserializeObject<List<Model.SysUserInfo>>(strSui);

                        #region 数据入库
                        using (var conn = new SqlConnection(connection))
                        {
                            conn.Open();
                            IDbTransaction transaction = conn.BeginTransaction();
                            try
                            {
                                lsui.ForEach(sui =>
                                {
                                    conn.Execute("insert into SysUserInfo(ID,UserCode,UserName,PassWord,SchoolID,GradeCode,GradeName,ClassID,ClassName,SubjectCode,SubjectName,RoleId,Card,Sex,Birthday,Nation,Origin,Political,Head,Motto,Remark,Eable,InputTime,LastInTime) values (@ID,@UserCode,@UserName,@PassWord,@SchoolID,@GradeCode,@GradeName,@ClassID,@ClassName,@SubjectCode,@SubjectName,@RoleId,@Card,@Sex,@Birthday,@Nation,@Origin,@Political,@Head,@Motto,@Remark,@Eable,@InputTime,@LastInTime)", sui, transaction);
                                });
                                transaction.Commit();
                                if (lsui.Count >= pageSize)
                                    return true;
                                else
                                    return false;
                            }
                            catch (Exception ex)
                            {
                                transaction.Rollback();
                                Log.errorlog(ex);
                            }
                            conn.Close();
                        }
                        #endregion
                    }
                }
                return false;
            };
            bool isGoOn = true;
            int pi = 1, pz = 100;
            do { isGoOn = DownSysUser(pi, pz); pi++; } while (isGoOn);
            return true;
        }
        /// <summary>
        /// 角色权限表
        /// </summary>
        /// <returns></returns>
        public bool GetSysRoleInfo()
        {
            using (WebClient wc = new WebClient())
            {
                wc.Encoding = System.Text.Encoding.GetEncoding("utf-8");
                string strSri = string.Empty;
                try
                {
                    strSri = wc.DownloadString(ConfigHelper.GetConfigString("RemoteUrl") + "/Ayyfford/GetSysRoleInfo");
                }
                finally
                {
                    wc.Dispose();
                }
                if (!string.IsNullOrWhiteSpace(strSri))
                {
                    var lsri = JsonConvert.DeserializeObject<List<Model.SysRoleInfo>>(strSri);

                    #region 数据入库
                    using (var conn = new SqlConnection(connection))
                    {
                        conn.Open();
                        conn.Execute("truncate table SysRoleInfo;");
                        IDbTransaction transaction = conn.BeginTransaction();
                        try
                        {
                            lsri.ForEach(sri =>
                            {
                                conn.Execute("insert into SysRoleInfo(Id,RoleName,RoleCode) values (@Id,@RoleName,@RoleCode)", sri, transaction);
                            });
                            transaction.Commit();
                            return true;
                        }
                        catch (Exception ex)
                        {
                            transaction.Rollback();
                            Log.errorlog(ex);
                        }
                        conn.Close();
                    }
                    #endregion
                }
            }
            return false;
        }
        #endregion

        #region 加载用户头像
        /// <summary>
        /// 加载用户头像
        /// </summary>
        /// <returns></returns>
        public bool DownHeadPhoto()
        {
            Action<object> downHead = (head) =>
            {
                if (!string.IsNullOrWhiteSpace(head as string))
                {
                    DownFileByRelativePath(head.ToString());
                }
            };

            Action<object> errHander = (state) =>
            {
                Log.errorlog(new Exception("用户编号为“" + state + "”的头像下载失败！"));
            };

            using (var conn = new SqlConnection(connection))
            {
                conn.Open();
                int pageIdx = 1, pageSize = 100, headNums = 0;
                do
                {
                    var heads = conn.Query<dynamic>(" select top " + (pageIdx * pageSize) + "  ID,Head  from SysUserInfo where ID not in(select top " + ((pageIdx - 1) * pageSize) + " ID from SysUserInfo order by ID asc) order by ID asc  ").ToList();
                    headNums = heads.Count();
                    pageIdx++;

                    heads.ForEach(item =>
                    {
                        FunHelper.TryAsync(downHead, item.Head, null, null, errHander, item.ID);
                    });

                } while (headNums >= pageSize);
                conn.Close();
            }
            return false;
        }
        #endregion

        #region 头像下载
        /// <summary>
        /// 头像下载
        /// </summary>
        /// <param name="resource"></param>
        void DownFileByRelativePath(string head)
        {
            try
            {
                head = "/" + head.Replace("\\", "/").Trim('/');
                if (string.IsNullOrWhiteSpace(head) || !head.IsFilePath())
                    return;
                FileDown<string> fd = new FileDown<string>(ConfigHelper.GetConfigString("RemoteUrl").TrimEnd('/') + "/" + head.TrimStart('/'), ConfigHelper.GetConfigString("SourceDir"), 10);
                fd.Data = head;
                fd.CallBack = (string _head) =>
                {

                };
                fd.Start();
            }
            catch (Exception ex)
            {
                Log.errorlog(ex);
            }
        }
        #endregion
    }
}
